<?php

/**
 * Plugin Name: Mi-publica
 * Description: This is a woocommerce clothing customization plug-in. Users can design clothing by uploading pictures of their own works.
 * Version: 1.0.4
 * Author: KURO
 * Author URI:
 */

require_once(plugin_dir_path(__FILE__) . 'setting.php');

function mi_publica_register_menu()
{
    add_menu_page(
        'Mi-publica',
        'Mi-publica',
        'manage_options',
        'Mi-publica',
        'mi_publica_settings_page_content',
        'dashicons-share-alt',
        99
    );
}
add_action('admin_menu', 'mi_publica_register_menu');

function enqueue_plugin_styles()
{
    $plugin_url = plugin_dir_url(__FILE__);
    $last_modified = filemtime(plugin_dir_path(__FILE__) . 'static/style.css');
    wp_enqueue_style('plugin-style', $plugin_url . 'static/style.css', array(), $last_modified);
    wp_enqueue_style('lightbox-style', $plugin_url . 'static/lightbox.min.css', array(), null);
}
add_action('wp_enqueue_scripts', 'enqueue_plugin_styles');
function enqueue_plugin_scripts()
{
    $plugin_url = plugin_dir_url(__FILE__);
    $last_modified = filemtime(plugin_dir_path(__FILE__) . 'static/main.js');
    wp_enqueue_script('plugin-script', $plugin_url . 'static/main.js', array(), $last_modified, true);
    wp_enqueue_script('lightbox-script', $plugin_url . 'static/lightbox.min.js', array(), null, true);
}
add_action('wp_footer', 'enqueue_plugin_scripts');


function load_custom_admin_style()
{
    $css_file_path = plugin_dir_path(__FILE__) . 'static/admin.css';
    $css_file_version = filemtime($css_file_path);
    wp_register_style('custom-admin-style', plugins_url('static/admin.css', __FILE__), array(), $css_file_version);
    wp_enqueue_style('custom-admin-style');
    wp_enqueue_style('lightbox-admin-style', plugin_dir_url(__FILE__) . 'static/lightbox.min.css', array(), null);
}
add_action('admin_enqueue_scripts', 'load_custom_admin_style');

function enqueue_plugin_admin_scripts()
{
    wp_enqueue_script('lightbox-admin-script', plugin_dir_url(__FILE__) . 'static/lightbox.min.js', array(), null, true);
}
add_action('admin_enqueue_scripts', 'enqueue_plugin_admin_scripts');



add_action('rest_api_init', function () {
    //:   /wp-json/mi-publica/v1/design/
    register_rest_route('mi-publica/v1', '/design', array(
        'methods' => 'GET',
        'callback' => 'handle_design_submission',
        'permission_callback' => '__return_true',
    ));
});
function handle_design_submission($data)
{
    if (class_exists('WooCommerce')) {
        $product_id = get_option('mi_publica_product_id');
        if (!$product_id) {
            echo "没有设置产品ID";
            return;
        }
        $product_url = get_permalink($product_id);
        if (!$product_url) {
            echo "产品不存在";
            return;
        }
        $design_img_url = isset($_GET['design_img']) ? $_GET['design_img'] : '';
        if (empty($design_img_url)) {
            echo "缺少设计图";
            return;
        }
        $design_id = isset($_GET['design_id']) ? $_GET['design_id'] : '';
        if (empty($design_id)) {
            echo "缺少设计ID";
            return;
        }
        $design_color = isset($_GET['design_color']) ? $_GET['design_color'] : '';
        if (empty($design_color)) {
            echo "缺少设计颜色";
            return;
        }
        setcookie('design_img', $design_img_url, 0, "/");
        setcookie('design_id', $design_id, 0, "/");
        setcookie('design_color', $design_color, 0, "/");
        wp_redirect($product_url);
        exit;
    } else {
        echo "请安装woocommerce";
        exit;
    }
}


add_action('woocommerce_before_add_to_cart_button', 'display_design_img_on_product_page');
function display_design_img_on_product_page()
{
    global $product;
    $product_id = get_option('mi_publica_product_id');
    if ($product->get_id() == $product_id) {
        woocommerce_form_field('design_img', array(
            'type' => 'hidden',
        ), '');
        woocommerce_form_field('design_id', array(
            'type' => 'hidden',
        ), '');
        woocommerce_form_field('design_color', array(
            'type' => 'hidden',
        ), '');
        $design_link = get_option('mi_publica_design_link');
//         echo '<div class="design-product-detail"><div class="design-row"><div class="design-title">Design:</div>';
        echo '<div class="design-product-detail"><div><div class="design-title">Design:</div>';
        echo '<div class="design-img-container design-img-box" data-design="' . $design_link . '"></div></div>';
        echo '</div>';
    }
}

add_filter('woocommerce_add_cart_item_data', 'add_design_img_to_cart_item', 10, 2);
function add_design_img_to_cart_item($cart_item_data, $product_id)
{
    if (isset($_POST['design_img']) && !empty($_POST['design_img'])) {
        $cart_item_data['design_img'] = sanitize_text_field($_POST['design_img']);
    }
    if (isset($_POST['design_id']) && !empty($_POST['design_id'])) {
        $cart_item_data['design_id'] = sanitize_text_field($_POST['design_id']);
    }
    if (isset($_POST['design_color']) && !empty($_POST['design_color'])) {
        $cart_item_data['design_color'] = sanitize_text_field($_POST['design_color']);
    }
    return $cart_item_data;
}



add_filter('woocommerce_get_item_data', 'display_design_img_in_cart_and_checkout', 10, 2);
function display_design_img_in_cart_and_checkout($cart_data, $cart_item)
{
    if (!empty($cart_item['design_img'])) {
        $cart_data[] = array(
            'name' => __('Design', 'woocommerce'),
            'value' => '<div class="order_meta_design"><a href="' . $cart_item['design_img'] . '" data-lightbox="image-1" data-title="Design" target=\"_blank\"><img src="' . $cart_item['design_img'] . '"></a></div>',
        );
    }
    if (!empty($cart_item['design_id'])) {
        $cart_data[] = array(
            'name' => __('Design ID', 'woocommerce'),
            'value' => "<div class=\"cart-design-value\">".$cart_item['design_id']."</div>",
        );
    }
    if (!empty($cart_item['design_color'])) {
        $cart_data[] = array(
            'name' => __('Design Color', 'woocommerce'),
            'value' => "<div class=\"cart-design-value\"><div class=\"design_color\" style=\"background-color:#".$cart_item['design_color']."\">".$cart_item['design_color']."</div></div>",
        );
    }
    return $cart_data;
}



add_action('woocommerce_checkout_create_order_line_item', 'save_design_img_to_order', 10, 4);

function save_design_img_to_order($item, $cart_item_key, $values, $order)
{
    if (isset($values['design_img'])) {
        $item->add_meta_data('design_img', $values['design_img']);
    }
    if (isset($values['design_id'])) {
        $item->add_meta_data('design_id', $values['design_id']);
    }
    if (isset($values['design_color'])) {
        $item->add_meta_data('design_color', $values['design_color']);
    }
}


add_filter('woocommerce_shop_order_list_table_columns', 'add_custom_order_column');
function add_custom_order_column($columns)
{
    $columns['design_img'] = 'Design';
    // $columns['design_id'] = 'Design ID';
    // $columns['design_color'] = 'Design Color';
    return $columns;
}

add_action('woocommerce_shop_order_list_table_custom_column', 'custom_order_column_content', 10, 2);
function custom_order_column_content($column, $order)
{
    if ($column == 'design_img') {
        $items = $order->get_items();
        $design_values = array();
        foreach ($items as $item_id => $item) {
            $design_values_item= array();
            $design_values_item['design_img'] = $item->get_meta('design_img', true);
            $design_values_item['design_id'] = $item->get_meta('design_id', true);
            $design_values_item['design_color'] = $item->get_meta('design_color', true);
            $design_values[] = $design_values_item;
        }

        if (!empty($design_values)) {
            $download_link = get_option('mi_publica_download_link');
            echo '<div class="order_list_meta_design">';
            foreach ($design_values as $design_value) {
                echo "<div class=\"design-row\"><div class=\"design-title\">Design:</div>";
                echo "<div class=\"design-img-container\"><a href='".$design_value['design_img']."' data-lightbox=\"image-1\" data-title=\"Design\" target=\"_blank\"><img src='".$design_value['design_img']."'></a></div>";
                echo "</div>";
                echo "<div class=\"design-row\"><div class=\"design-title\">Design color:</div><div class=\"design-value\"><div class=\"design_color\"  style=\"background-color:#".$design_value['design_color']."\">".$design_value['design_color']."</div></div></div>";
                $download_link_url = $download_link."?artNo=" . $design_value['design_id']. "&orderNo=" . $order->get_id();
                echo "<div class=\"design-row\"><div class=\"design-title\">Design Id:</div><div class=\"design-value\"><a href=\"$download_link_url\" target=\"_blank\">".$design_value['design_id']."</a></div></div>";
            }
            echo '</div>';
        } else {
            echo __('No design images found for this order.', 'woocommerce');
        }
    }
}

add_action('woocommerce_order_item_display_meta_value', 'customize_order_item_meta_value', 10, 3);
function customize_order_item_meta_value($display_value, $meta, $item)
{
    if ('design_img' === $meta->key) {
        $design_img = $meta->value;
        $display_value = "<div class=\"order_meta_design\"><a href='$design_img' data-lightbox=\"image-1\" data-title=\"Design\" target=\"_blank\"><img src='$design_img'></a></a>";
    }
    if ('design_color' === $meta->key) {
        $design_color = $meta->value;
        $display_value = "<div class=\"design_color\" style=\"background-color:#$design_color\">$design_color</div>";
    }
    if ('design_id' === $meta->key) {
        $design_id = $meta->value;
        $download_link = get_option('mi_publica_download_link');
        $download_link_url = $download_link."?artNo=" . $design_id. "&orderNo=" . $item->get_order_id();
        $display_value = "<a href='".$download_link_url."' target=\"_blank\">$design_id</a>";
    }

    return $display_value;
}
add_action('woocommerce_order_item_display_meta_key', 'customize_order_item_meta_key', 10, 3);
function customize_order_item_meta_key($display_key, $meta, $item)
{
    if ('design_img' === $meta->key) {
        $display_key = "Design Images";
    }
    if ('design_color' === $meta->key) {
        $display_key = "Design Color";
    }
    if ('design_id' === $meta->key) {
        $display_key = "Design ID";
    }
    return $display_key;
}



//add_action('woocommerce_after_cart_item_name', 'add_design_after_cart_item_name',10,2);
function add_design_after_cart_item_name($cart_item, $cart_item_key)
{
    if (!empty($cart_item['design_img'])) {
        echo '<div class="order_meta_design"><a href="' . $cart_item['design_img'] . '" data-lightbox="image-1" data-title="Design" target=\"_blank\"><img src="' . $cart_item['design_img'] . '"></a></div>';
    }
}


function custom_button_shortcode()
{
    $design_link_text = get_option('mi_publica_link_text');
    $design_link = get_option('mi_publica_design_link');
    if (empty($design_link_text)) {
        $design_link_text = "设计";
    }
    $button_html = '<a href="' . $design_link . '" class="goDesignBtn">' . $design_link_text . '</a>';
    return $button_html;
}
add_shortcode('design_link_button', 'custom_button_shortcode');


add_action( 'woocommerce_checkout_order_processed', 'clear_cookie_on_order_submission', 10, 1 );
function clear_cookie_on_order_submission( $order_id ) {
    $order = wc_get_order( $order_id );
    $product_id = get_option('mi_publica_product_id');
    $specified_product_id = $product_id;
    $contains_specified_product = false;

    foreach( $order->get_items() as $item ) {
        if ( $item->get_product_id() == $specified_product_id ) {
            $contains_specified_product = true;
            break;
        }
    }

    if ( $contains_specified_product ) {
        unset( $_COOKIE['design_img'] );
        setcookie( 'design_img', '', time() - 3600, '/' );

        unset( $_COOKIE['design_id'] );
        setcookie( 'design_id', '', time() - 3600, '/' );

        unset( $_COOKIE['design_color'] );
        setcookie( 'design_color', '', time() - 3600, '/' );
    }
}
